package com.ng.sys.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.ng.sys.model.domain.*;
import com.ng.sys.service.IUser;

@Service
public class UserImpl implements IUser {

	public User getById(String id) {
		return User.dao.findById(id);

	}

	public List<User> list(User param) {
		String _sql="select id,name,username,phone,pid,is_limit,status,role_mark,token from " + User.TABLE_NAME + " where pid=? ";
		if(StrKit.equals("-1", param.getId())) {
			if(!StrKit.isBlank(param.getName())) {
				_sql="select * from " + User.TABLE_NAME + " where pid=? and  name like '%"+param.getName()+"%' ";
			}
		}else {
			_sql="select id,name,username,phone,pid,is_limit,status,role_mark,token from " + User.TABLE_NAME + " where id=? ";
		}
		
		List<User> users = User.dao.find(_sql, param.getId());
		for (User u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		} 
		return users;
	}
	
	
	public List<User> getChildrens(User param) {
		String _sql="select id,name,username,phone,pid,is_limit,status,role_mark,token from " + User.TABLE_NAME + " where pid=? ";
		if(!StrKit.isBlank(param.getName())) {
			_sql="select * from " + User.TABLE_NAME + " where pid=? and  name like '%"+param.getName()+"%' ";
		}
		List<User> users = User.dao.find(_sql, param.getId());
		for (User u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		}
		return users;
	}
	
	@Override
	public boolean delete(String  id) {
		Db.delete("delete from "+UserRole.TABLE_NAME+" where user_id=?",id);
		Db.delete("delete from "+User.TABLE_NAME+" where id=?",id);
		return false;
	}

	@Override
	public Optional<User> findUserByUsername(String username) {
		return  Optional.ofNullable(User.dao.findFirst("select * from "+User.TABLE_NAME+" where username=?", username));
	}
}
